//
//  WDHolderTextView.swift
//  UIKitExtentions
//
//  Created by Alean on 2023/4/27.
//

import UIKit

public class WDHolderTextView: UITextView {
    public var placeholder: String? {
        didSet {
            self.setNeedsDisplay()
        }
    }
    public var placeholderColor: UIColor? = UIColor.lightGray {
        didSet {
            self.setNeedsDisplay()
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    public override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextView.textDidChangeNotification, object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    public override func draw(_ rect: CGRect) {
        if self.hasText {
            return
        }
        if let placeholder = placeholder {
            let attrs: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor: self.placeholderColor as Any, NSAttributedString.Key.font: self.font!]
            
            var rect1 = rect
            rect1.origin.x = 5
            rect1.origin.y = 8
            rect1.size.width = rect1.size.width - 2 * rect1.origin.x
            (placeholder as NSString).draw(in: rect1, withAttributes: attrs)
        }
    }
    
    @objc func textDidChange(_ note: Notification) {
        self.setNeedsDisplay()
    }
}
